package com.zjzywl.smoke.manager;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zjzywl.smoke.repository.AlarmRepository;
import com.zjzywl.smoke.entity.Alarm;

@Component
public class AlarmManager {

	public Integer occurAlarm(Alarm a) {
		// 移除并且保存原先同设备报警
		removeAlarm(a);
		// 增加新报警
		return Append(a);
	}

	// 设备恢复正常，移除所有该报警
	public Integer backToNormal(String alarmcode) {
		return removeDeviceAlarm(alarmcode);
	}

	public AlarmManager() {
		// 从数据库中拉取未结束报警

	}

	public void loadAlarm() {
		alarms = alarmRepository.findByEndTimeIsNull();
		System.out.println("loadAlarm:" + alarms.size());
	}

	@Autowired
	private AlarmRepository alarmRepository;

	// 存储报警数据
	private static List<Alarm> alarms = null;

	// 增加报警
	private Integer Append(Alarm alarm) {
		synchronized (alarms) {
			alarms.add(alarm);
			System.out.println("Append:" + alarm.toString());
		}
		return alarms.size();
	}

	// 移除设备所有报警
	private Integer removeDeviceAlarm(String alarmcode) {
		synchronized (alarms) {
			Iterator<Alarm> it = alarms.iterator();
			while (it.hasNext()) {
				Alarm a = it.next();
				if (a.getDevice().getDevCode().equals(alarmcode)) {

					// 获取这个报警最新数据
					Alarm newest = alarmRepository.findOne(a.getAlarmId());
					if (newest != null) {
						newest.setEndTime(new Date());
						alarmRepository.save(newest);
					}
					System.out.println("removeDeviceAlarm:" + a.toString());
					it.remove();
				}
			}
		}
		return alarms.size();
	}

	// 移除设备同类型报警
	private Integer removeAlarm(Alarm alarm) {
		synchronized (alarms) {
			Iterator<Alarm> it = alarms.iterator();
			while (it.hasNext()) {
				Alarm a = it.next();
				if ((a.getDevice().getDevCode().equals(alarm.getDevice().getDevCode()))
						&& (a.getAlarmType().getAlarmCode().equals(alarm.getAlarmType().getAlarmCode()))) {

					Alarm newest = alarmRepository.findOne(a.getAlarmId());
					if (newest != null) {
						newest.setEndTime(new Date());
						alarmRepository.save(newest);
					}
					System.out.println("removeAlarm:" + a.toString());
					it.remove();
					break;
				}
			}
		}
		return alarms.size();
	}
}
